package com.itheima.sc.service.pms;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.sc.api.pms.ProductCategoryApi;
import com.itheima.sc.config.ComException;
import com.itheima.sc.pojo.pms.ProductAttributeCategory;
import com.itheima.sc.pojo.pms.ProductCategory;
import com.itheima.sc.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductCategoryService {
    @DubboReference
    private ProductCategoryApi categoryApi;

    //添加商品分类
    public void create(ProductCategory category) {
        //处理parentId属性,level属性
        if (category.getParentId()==0){
            category.setLevel(0);
        }else {
            category.setLevel(1);
        }
        category.setProductCount(0);
        categoryApi.save(category);
    }

    //删除商品分类
    public void deleteById(Integer id) {

        //删除分类判断,如果有产品,不能删除
        ProductCategory category = categoryApi.getById(Convert.toLong(id));
        if (ObjectUtil.isNotEmpty(category.getProductCount()) && category.getProductCount()>0){
            throw new ComException("当前分类含有商品,不可删除");
        }

        categoryApi.removeById(id);
    }

    //查询所有一级分类及子分类
    public List<ProductCategory> listWithChildren() {
        List<ProductCategory> categoryList = categoryApi.listWithChildren();
        return categoryList;
    }

    //根据parentId分页查询商品分类
    public PageResult listByParentId(Integer parentId, Integer pageNum, Integer pageSize) {
        List<ProductCategory> list= categoryApi.listByParentId(parentId,pageNum,pageSize);

        //根据parentId查询totalCount
        Integer total = categoryApi.getCount(parentId);
        Integer totalPage = total/pageNum+1;
        //封装pageResult
        PageResult<ProductCategory> pageResult = new PageResult<>(pageNum, pageSize, total, totalPage, list);
        return pageResult;
    }

    //修改导航栏显示状态
    public void updateNavStatus(Integer navStatus, List<Integer> ids) {
        categoryApi.updateNavStatus(navStatus,ids);
    }

    //修改显示状态
    public void updateShowStatus(Integer showStatus, List<Integer> ids) {
        categoryApi.updateShowStatus(showStatus,ids);
    }

    //修改商品分类
    public void updateById(Integer id, ProductCategory category) {
        category.setId(Convert.toLong(id));
        categoryApi.updateById(category);
    }

    //根据id获取商品分类
    public ProductCategory getById(Integer id) {
        ProductCategory category = categoryApi.getById(id);
        return category;
    }


}
